define(['jquery', 'bootstrap', 'backend', 'table', 'form','clipboard','layui'], function ($, undefined, Backend, Table, Form,ClipboardJS,Layui) {
    const searchkeywords = function () {
        return new Promise(resolve => {
            $.getJSON('article.articles/searchlist').done(res => {
                resolve(res)
            })
        })
    };
    var Controller = {
        index: async function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'article.articles/index' + location.search,
                    add_url: 'article.articles/add',
                    edit_url: 'article.articles/edit',
                    del_url: 'article.articles/del',
                    multi_url: 'article.articles/multi',
                    table: 'articles',
                }
            });

            var table = $("#table");

             //当表格数据加载完成时
             table.on('load-success.bs.table', function (e, data) {
                  /*if(data.html!=''&&data.html!=null){
                     $("#createhtml").html(data.html);
                   }*/
              });

            // 初始化表格
            //,events: Controller.api.events.copy, formatter: Controller.api.formatter.copy
            //,sortable:true  ,visible:false  , operate:'LIKE %...%'  ,custom:{'0':'success','1':'danger'}
            // ,placeholder: '关键字，模糊搜索', operate:'FIND_IN_SET'
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //searchFormVisible: true, //是否始终显示搜索表单
                fixedColumns: true,
                fixedRightNumber: 1,
                //pageSize: 15,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),sortable:true},
                        {
                            field: 'category_id',
                            title: __('栏目'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="category/selectpage" data-field="name"',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        /*{field: 'category_id', title: __('Category_id')},*/
                        {field: 'title', title: __('Title'), operate:'LIKE %...%', formatter: function(value,row){
                                return '<a href="'+row.url+'" target="_blank"><strong style="color: '+row.title_color+'">'+value+'</strong></a>';
                            }},
                        {field: 'category.name', title: __('栏目'), formatter: Table.api.formatter.label, operate:false},

                        /*{field: 'title_color', title: __('Title_color')},*/
                        {field: 'keywords', title: __('Keywords'), searchList: await searchkeywords(), operate:'=',formatter: Table.api.formatter.label},
                       /* {field: 'description', title: __('Description')},*/
                        {
                            field: 'img_url',
                            title: __('Img_url'),
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image,
                            operate: false
                        },
                        {field: 'origin', title: __('Origin'),custom:{'原创':'success','转载':'grey'}, formatter: Table.api.formatter.label},
                       /* {field: 'content', title: __('Content')},*/
                        {field: 'is_recommend', title: __('Is_recommend'), searchList: {"1":__('Is_recommend 1'),"0":__('Is_recommend 0')}, formatter: Table.api.formatter.status},
                        {field: 'is_top', title: __('Is_top'), searchList: {"1":__('Is_top 1'),"0":__('Is_top 0')}, formatter: Table.api.formatter.status},
                        {field: 'is_show', title: __('Is_show'), searchList: {"1":__('Is_show 1'),"0":__('Is_show 0')}, formatter: Table.api.formatter.status},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"0":__('Status 0')}, formatter: Table.api.formatter.status},
                        {field: 'is_tui', title: __('Is_tui'), searchList: {"0":__('Is_tui 0'),"1":__('Is_tui 1'),"2":__('Is_tui 2')}, formatter: Table.api.formatter.status},
                        {field: 'hits', title: __('Hits'),sortable:true},
                        {field: 'love', title: __('Love'),sortable:true},
                        {field: 'comment_num', title: __('Comment_num'),sortable:true},
                        {field: 'author', title: __('Author')},
                       /* {field: 'url', title: __('Url'), formatter: Table.api.formatter.url},*/
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                       /* {field: 'updatetime', title: __('Updatetime'), operate:false, addclass:'datetimerange', formatter: Table.api.formatter.datetime},*/
                        {field: 'operate', title: __('Operate'), table: table
                            ,events: {
                                'click .btn-check_tuisong': function (e, value, row) {
                                    var m='确定推送该文章？';
                                    Layer.confirm(m,function (index) {
                                        Layer.close(index);
                                        Fast.api.ajax({
                                            url: "article.articles/tuisong",
                                            data: {id: row.id},
                                        }, function (data, ret) {
                                            table.bootstrapTable('refresh');
                                        },function (data,ret) {
                                            table.bootstrapTable('refresh');
                                        });
                                    })
                                    return false;
                                },
                                'click .btn-check_delete': function (e, value, row) {
                                    var m='确定删除推送该文章？';
                                    Layer.confirm(m,function (index) {
                                        Layer.close(index);
                                        Fast.api.ajax({
                                            url: "article.articles/check_delete",
                                            data: {id: row.id},
                                        }, function (data, ret) {
                                            table.bootstrapTable('refresh');
                                        },function (data,ret) {
                                            table.bootstrapTable('refresh');
                                        });
                                    })
                                    return false;
                                },
                            } ,buttons: [
                                {
                                    name: 'check_tuisong',
                                    text: __('推送'),
                                    classname: 'btn btn-xs btn-success btn-check_tuisong',
                                    // icon:'fa fa-cancer',
                                    title:__('推送到百度'),
                                    visible: function (row) {
                                        if (row.is_tui=='0'){
                                            return  true;
                                        }
                                        return false;
                                    },
                                },
                                {
                                    name: 'check_delete',
                                    text: __('取消推送'),
                                    classname: 'btn btn-xs btn-danger btn-check_delete',
                                    // icon:'fa fa-cancer',
                                    title:__('取消推送到百度'),
                                    visible: function (row) {
                                        if (row.is_tui=='1'){
                                            return  true;
                                        }
                                        return false;
                                    },
                                }
                            ]
                            ,formatter: function (value, row, index) { //隐藏自定义的视频按钮
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                //权限判断
                                if(Config.check_tuisong != true){  //通过Config.chapter 获取后台存的chapter
                                    $(table).data("operate-check_tuisong", null);
                                    that.table = table;
                                }
                                if(Config.check_delete != true){  //通过Config.chapter 获取后台存的chapter
                                    $(table).data("operate-check_delete", null);
                                    that.table = table;
                                }
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }},
                       /* {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}*/
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            //移动
            $(document).on('click', '.btn-move', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Move'),
                    content: Template("channeltpl", {}),
                    btn: [__('Move')],
                    yes: function (index, layero) {
                        var channel_id = $("select[name='channel']", layero).val();
                        if (channel_id == 0) {
                            Toastr.error(__('Please select channel'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "article.articles/move",
                            type: "post",
                            data: {category_id: channel_id,ids:ids.join(",")},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'article.articles/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'article.articles/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'article.articles/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
           bindevent: function () {
               Layui.use(['form', 'upload','colorpicker'], function (form, upload) {
                   var q = layui.$
                       ,colorpicker = layui.colorpicker;
                   //背景颜色
                   colorpicker.render({
                       elem: '#c-background'
                       ,done: function(color){
                           var cont=$("#c-title").val();
                           var str="<span style='color: "+color+"'>"+cont+"</span>";
                           $("#text_show").html(str);
                           $('#c-title_color').val(color);
                       }
                   });
               });
               Form.api.bindevent($("form[role=form]"));
           },
           formatter:{
                copy:function (value,row,index) {
                    var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "250px";
                    var copy_but=__('Click copy');
                    if (value=="" ||value==null ||value =='null') value ='-';
                        return '<button class="btn btn-copy btn-xs bg-success" data-clipboard-text="'+value+'" data-original-title="'+copy_but+'" data-toggle="tooltip">' +
                               '<div style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:"'+ width +'";>'+ value +' </div>' +
                                '</button>';
                }
           },
           events:{
               copy:{
                    'click .btn-copy':function (e,value,row,index) {
                          var clipboard=new ClipboardJS(".btn");
                           Toastr.info(__("Copy successfully"));
                     }
                }
           }
         }
    };


    $('.btn-tags').click(function () {
         var url='article.tags/add';
         Backend.api.open(url,'添加文章标签');
    });

    //单选按钮
    $('input:radio[name="row[origin]"]').click(function(){
        var checkValue = $('input:radio[name="row[origin]"]:checked').val();
        if (checkValue=='原创'){
            $(".origin").hide(0);
        }else{
            $(".origin").show(0);
        }
    });




    return Controller;
});